<template>
  <!-- 工程管理页面 -->
  <div>
    <!-- 同步模块数据窗口 -->
    <el-dialog
      v-dialogDrag
      title="应用管理"
      :visible.sync="isAppMag"
      width="514px"
    >
      <upper-template noIcon>
        <div slot="buttonArea">
          <el-button @click="addAppFunc">新增</el-button>
        </div>
      </upper-template>
      <el-table :data="appList">
        <el-table-column label="数据源" prop="dsName"></el-table-column>
        <el-table-column
          label="应用模块"
          prop="moduleCode"
          :formatter="
            row =>
              $getLabel(row.moduleCode, moduleList, 'moduleCode', 'moduleName')
          "
        ></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-link type="danger" @click="delAppRow(scope.$index)"
              >移除</el-link
            >
          </template>
        </el-table-column>
      </el-table>

     
      <!-- 每条应用录入弹窗 -->
      <el-dialog
        title="应用管理新增"
        v-dialogDrag
        :visible.sync="addAppDialog"
        width="514px"
        append-to-body
      >
        <el-form
          :model="appMagForm"
          ref="appMagForm"
          label-width="97px"
          label-position="left"
          :rules="appMagFormRule"
        >
          <el-row>
            <el-col :span="18" :offset="4">
              <el-form-item label="工程名：" prop="projectName">
                <el-input
                  v-model="appMagForm.projectName"
                  placeholder=""
                  disabled
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="18" :offset="4">
              <el-form-item label="应用模块：" prop="moduleCode">
                <el-select
                  v-model="appMagForm.moduleCode"
                  @change="appModuleChange"
                  style="width:100%"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in moduleList"
                    :key="item.moduleCode"
                    :label="item.moduleName"
                    :value="item.moduleCode"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="18" :offset="4">
              <el-form-item label="数据源：" prop="dsName">
                <el-select
                  v-model="appMagForm.dsName"
                  style="width:100%"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in dataSrcList"
                    :key="item.dsName"
                    :label="item.dsName"
                    :value="item.dsName"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer">
          <el-button type="primary" @click="pushToAppList">确 定</el-button>
          <el-button @click="addAppDialog = false">取 消</el-button>
        </div>
      </el-dialog>
       <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveAppList">确 定</el-button>
        <el-button @click="isAppMag = false">取 消</el-button>
      </div>
    </el-dialog>
      <el-row>
        <el-col :span="24">
          <upper-template
            @search="searchFF.page=1,searchFunc_data()"
            :configIcon="false"
            @clear="(searchFF.datasourceName = ''), (searchFF.moduleCode = '')"
          >
            <div slot="buttonArea">
              <el-button @click="sync_dataSrc">同步数据源</el-button>
              <el-button @click="addFunc_data">新增</el-button>
              <el-button @click="editFunc_data">编辑</el-button>
              <el-button @click="delFunc_data">删除</el-button>
            </div>
            <div slot="searchArea">
              <el-form
                :model="searchFF"
                ref="searchFF"
                label-width="120px"
                label-position="left"
                size="mini"
              >
                <el-form-item label="数据源名称：">
                  <el-input
                    v-model="searchFF.datasourceName"
                    placeholder="请输入名称"
                  ></el-input>
                </el-form-item>
                <el-form-item label="应用模块：">
                  <el-select
                    v-model="searchFF.moduleCode"
                    placeholder="请选择模块"
                    style="width:100%"
                  >
                    <el-option
                      v-for="item in moduleList"
                      :key="item.moduleName"
                      :label="item.moduleName"
                      :value="item.moduleCode"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-form>
            </div>
          </upper-template>
          <el-table
            ref="dataSrcTable"
            :data="dataSrcTableData"
            style="width: 100%"
            @row-click="dataSrcTableRowClick"
          >
            <el-table-column
              width="55"
              type="selection"
              
            ></el-table-column>
             <el-table-column prop="dataSourceName" label="数据源名称"
             show-overflow-tooltip 
            >
            </el-table-column>
            <el-table-column prop="moduleCode" label="应用模块">
            </el-table-column>
            <el-table-column prop="url" label="数据源url" show-overflow-tooltip>
            </el-table-column>
            <el-table-column prop="username" label="用户"> </el-table-column>
            <el-table-column prop="datasourceType" label="数据库类型">
            </el-table-column>
          </el-table>
          <pagination
            @size-change="handleSizeChange_data"
            @current-change="handleCurrentChange_data"
            :pager-count="5"
            @refresh="searchFunc_data"
            :current-page="searchFF.page"
            :page-size="searchFF.size"
            :total="total_"
          ></pagination>
        </el-col>
      </el-row>

      <el-dialog
        :title="saveFlg_data == 1 ? '新增数据源' : '编辑数据源'"
        append-to-body
        :visible.sync="isDataSrcMagAddOrEdit"
        width="514px"
      >
        <el-form
          :model="saveForm_data"
          ref="saveForm_data"
          label-width="120px"
          label-position="left"
          size="mini"
          :rules="saveForm_dataRules"
        >
          <h2 style="height: 20px;font-size:14px">
            <span class="vertical-bar"></span> 基础参数
          </h2>
          <!-- <el-form-item label="数据源名称：" prop="dataSourceName">
            <el-input v-model="saveForm_data.dataSourceName"></el-input>
          </el-form-item> -->
          <el-form-item label="应用模块：" prop="moduleCode">
            <el-select
              v-model="saveForm_data.moduleCode"
              placeholder="请选择模块"
              style="width:100%"
            >
              <el-option
                v-for="item in moduleList"
                :key="item.moduleName"
                :label="item.moduleName"
                :value="item.moduleCode"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="数据源名称：">

            <!-- <el-input v-model="saveForm_data.dataSourceName"></el-input> -->
              <el-form-item
                style="display: inline-block;"
              >
                <el-input
                  v-model="saveForm_data.moduleCode"
                  readonly
                  style="width:120px;"
                ></el-input>
              </el-form-item>

              <span style="padding: 6px;">-</span>
              <el-form-item prop="dataSourceNameLast" style="display: inline-block;">
                <el-input
                  maxlength="20"
                  v-model="saveForm_data.dataSourceNameLast"
                  style="width:210px;"
                ></el-input>
              </el-form-item>
          </el-form-item>
          <el-form-item label="数据源url：" prop="url">
            <el-input v-model.trim="saveForm_data.url"></el-input>
          </el-form-item>
          <el-form-item label="用户：" prop="username">
            <el-input v-model.trim="saveForm_data.username"></el-input>
          </el-form-item>
          <el-form-item label="密码：" prop="password">
            <el-input
             @focus="passwordClick"
              v-model.trim="saveForm_data.password"
              type="password"
            ></el-input>
          </el-form-item>
          <el-form-item label="数据库类型：" prop="datasourceType">

            <!-- <el-input v-model.trim="saveForm_data.datasourceType"></el-input> -->
               <el-select
                    v-model="saveForm_data.datasourceType"
                    placeholder="请选择"
                    style="width: 100%"
                  >
                    <el-option
                      v-for="item in dataSourceTypeList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    >
                    </el-option>
                  </el-select>
          </el-form-item>
          <h2 style="height: 20px;font-size:14px">
            <span class="vertical-bar"></span> 其他参数
          </h2>
          <el-form-item label="初始线程数：" prop="initialSize">
            <el-input v-model="saveForm_data.initialSize"></el-input>
          </el-form-item>
          <el-form-item label="最大线程数：" prop="maxActive">
            <el-input v-model="saveForm_data.maxActive"></el-input>
          </el-form-item>
          <el-form-item label="最小空闲数：" prop="minIdle">
            <el-input v-model="saveForm_data.minIdle"></el-input>
          </el-form-item>
          <el-form-item label="最大空闲数：" prop="maxIdle">
            <el-input v-model="saveForm_data.maxIdle"></el-input>
          </el-form-item>
          <el-form-item label="最大等待时间：" prop="maxWait">
            <el-input v-model="saveForm_data.maxWait"></el-input>
          </el-form-item>
          <el-form-item
            label="重新检测时间："
            prop="timeBetweenEvictionRunsMillis"
          >
            <el-input
              v-model="saveForm_data.timeBetweenEvictionRunsMillis"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="最小生存时间："
            prop="minEvictableIdleTimeMillis"
          >
            <el-input
              v-model="saveForm_data.minEvictableIdleTimeMillis"
            ></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer">
          <el-button @click="saveFunc_data">确定</el-button>
          <el-button @click="saveFunc_test">测试连接</el-button>
          <el-button @click="isDataSrcMagAddOrEdit = false">取消</el-button>
        </div>
      </el-dialog>
    <!-- </el-dialog> -->
  </div>
</template>

<script>
import { systemManage } from "@/api/index";
import sm4 from '@/lib/gmsm4/index'
export default {
  data() {
    return {
      dataSourceTypeList: [], // 数据库驱动集合
      userDo: "授权角色", // 右侧用户行为
      editFlag: 1,
      userDoFlag: 0,
      addOrEdit: false, // 新增/编辑/查看弹窗
      isAppMag: false, //同步模块数据弹窗
      serachMore: false,
      isDataSrcMag: false, //工程表配置弹窗
      isDataSrcMagAddOrEdit: false,
      addAppDialog: false,
      saveFlg: 1, // 1:新增，2：编辑，3查看,
      saveFlg_data: 1,
      saveTitles: ["添加工程信息", "编辑工程信息"],
      appList: [],
      appMagForm: {
        projectId: "",
        projectName: "",
        moduleCode: "",
        dsName: ""
      },
      appMagFormRule: {
        projectName: [
          { required: true, message: "该输入项为必输项", trigger: "blur" }
        ],
        moduleCode: [
          { required: true, message: "该输入项为必输项", trigger: "blur" }
        ],
        dataSourceId: [
          { required: true, message: "该输入项为必输项", trigger: "blur" }
        ]
      },
      dataSrcList: [],
      searchForm: {
        projectName: "",
        projectId: "",
        page: 1,
        size: 15
      },
      total: 1,
      searchFF: {
        datasource: "",
        moduleCode: "",
        page: 1,
        szie: 15
      },
      total_: 0,
      saveForm: {
        projectId: "",
        projectName: "",
        remark: ""
      },
      key: '00000000000000000000000000000000',
      saveForm_data: {
        dataSourceId: "",
        dataSourceName: "",
        datasourceType: "",
        initialSize: "",
        maxActive: "",
        maxIdle: "",
        maxWait: "",
        minEvictableIdleTimeMillis: "",
        minIdle: "",
        moduleCode: "",
        password: "",
        timeBetweenEvictionRunsMillis: "",
        url: "",
        username: "",
        dataSourceNameLast: "",
      },
      saveFormRules: {
        // projectId: [
        //   { required: true, message: "该输入项为必输项", trigger: "blur" },
        // ],
        projectName: [
          { required: true, message: "该输入项为必输项", trigger: "blur" },
          {
            pattern: /^[\u4E00-\u9FA5A-Za-z0-9]{1,40}$/,
            message: "只能输入1-40位中文、字母、数字或下划线",
            trigger: "blur"
          }
          // { validator: this.projectNameValid, trigger: "blur" }
        ]
      },
      saveForm_dataRules: {
        dataSourceNameLast: [
          { required: true, message: "请输入数据源名称", trigger: "blur" },
          // {
          //   pattern: /^[\u4E00-\u9FA5A-Za-z0-9]{1,40}$/,
          //   message: "只能输入1-40位中文、字母、数字或下划线",
          //   trigger: "blur"
          // }
        ],
        moduleCode: [
          { required: true, message: "请选择模块", trigger: "blur" }
        ],
        url: [{ required: true, message: "请输入数据源url", trigger: "blur" }],
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" }
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur"}],
        datasourceType: [
          { required: true, message: "请选择数据库类型", trigger: "blur" }
        ],
        initialSize: [
          { pattern: /^[0-9]+$/, message: "只能输入数字", trigger: "blur" }
        ],
        maxActive: [
          { pattern: /^[0-9]+$/, message: "只能输入数字", trigger: "blur" }
        ],
        maxIdle: [
          { pattern: /^[0-9]+$/, message: "只能输入数字", trigger: "blur" }
        ],
        minIdle: [
          { pattern: /^[0-9]+$/, message: "只能输入数字", trigger: "blur" }
        ],
        maxWait: [
          { pattern: /^[0-9]+$/, message: "只能输入数字", trigger: "blur" }
        ],
        minEvictableIdleTimeMillis: [
          { pattern: /^[0-9]+$/, message: "只能输入数字", trigger: "blur" }
        ],
        timeBetweenEvictionRunsMillis: [
          { pattern: /^[0-9]+$/, message: "只能输入数字", trigger: "blur" }
        ]
      },
      checkList: [],
      // 完整表头字段&&列属性配置
      textData: [
        { prop: "projectId", label: "工程号" },
        { prop: "projectName", label: "工程名称" },
        { prop: "remark", label: "备注" },
        { prop: "moduleName", label: "授权应用" },
        { prop: "status", label: "锁定状态" }
      ],
      // 获取table的数据
      tableData: [],
      dataSrcTableData: [],
      moduleList: [],
    };
  },
  created() {
    this.checkListInit();
    this.queryInitData();
    this.getDict()
    this.$nextTick(() => {
      this.searchFunc();
    });
  },
  computed: {
    tablePick() {
      return this.$tableDataPick(this.checkList, this.textData);
    }
  },
  mounted() {
    // this.getList();
      this.searchFunc_data();
  },
  watch: {
    addOrEdit() {
      // 窗口打开或关闭清除校验结果
      if (this.$refs.saveForm) {
        this.$refs.saveForm.clearValidate();
      }
    },
    isAppMag() {
      // 窗口打开或关闭清除校验结果
      if (this.$refs.appMagForm) {
        this.$refs.appMagForm.clearValidate();
      }
    },
    isDataSrcMagAddOrEdit() {
      // 窗口打开或关闭清除校验结果
      if (this.$refs.saveForm_data) {
        this.$refs.saveForm_data.clearValidate();
      }
    }
  },
  methods: {
    passwordClick(){
      if(this.saveFlg_data == 2){
        if(this.editFlag == 0) {
          this.editFlag = 1
          this.saveForm_data.password = ''
        } 
      }
    },
    getDict(){
       // 数据库驱动集合
      this.$getDict("DATASOURCE_TYPE").then((res) => {
        if (res.code == 200) {
          this.dataSourceTypeList = res.datas;
        }
      });
    },
    queryInitData() {
      // 查询初始化数据，字典下拉框等
      systemManage.queryAllEnableModules().then(res => {
        if (res.code == 200) {
          this.moduleList = res.datas;
        }
      });
    },
    checkListInit() {
      this.checkList = this.textData.map(v => {
        return v.label;
      });
    },
    // 查询所有可用工程
    queryAllUsefulProject() {
      systemManage.queryAllUsefulProject().then(res => {});
    },
    projectNameValid(rule, val, callback) {
      // 只在新增时校验
      // if (this.saveFlg != 1) {
      //   callback();
      //   return;
      // }
      let data = {
        projectId: this.saveForm.projectId,
        projectName: val
      };
      systemManage.checkProjectName(data).then(res => {
        if (res.code == 200) {
          callback();
        } else {
          callback(new Error("名称已存在"));
        }
      });
    },
    searchFunc() {
      let data = this.searchForm;
      systemManage.projectQuery(data).then(res => {
        this.tableData = res.datas.rows;
        this.total = res.datas.total;
      });
    },
    addFunc() {
      this.saveFlg = 1;
      for (let k in this.saveForm) {
        this.saveForm[k] = "";
      }
      this.addOrEdit = true;
    },
    rowClick(row) {
      if (this.$refs.multipleTable) {
        this.$refs.multipleTable.clearSelection();
        this.$refs.multipleTable.toggleRowSelection(row, true);
      }
    },
    delAppRow(index) {
      this.appList.splice(index, 1);
    },
    appMag() {
      let slection = this.$refs.multipleTable.selection;
      if (slection.length != 1) return this.$message.warning("请选择一条数据");
      for (const k in this.appMagForm) {
        this.appMagForm[k] = "";
      }
      this.appMagForm.projectName = slection[0].projectName;
      this.appMagForm.projectId = slection[0].projectId;
      this.appList = this.$clone(slection[0].moduleDatasources);
      this.isAppMag = true;
    },
    dataSrcMag() {
      this.isDataSrcMag = true;
      this.searchFunc_data();
    },
    //    数据源管理 ↓
    searchFunc_data() {
      let data = this.searchFF;
      systemManage.dataSrcQueryAllDsForPage(data).then(res => {
        if (res.code == 200) {
          this.dataSrcTableData = res.datas.rows;
          this.total_ = res.datas.total;
        }
      });
    },
    sync_dataSrc() {
      systemManage.dataSrcSyncAllDs().then(res => {
        if (res.code == 200) {
          this.$message.success("同步成功");
          this.searchFunc_data();
        } else {
          this.$message.error(res.message || "失败");
        }
      });
    },
    addFunc_data() {
      this.saveFlg_data = 1;
      this.isDataSrcMagAddOrEdit = true;
      for (const k in this.saveForm_data) {
        this.saveForm_data[k] = "";
      }
    },
    editFunc_data() {
      this.editFlag = 0,
      this.saveFlg_data = 2;
      let slec = this.$refs["dataSrcTable"].selection;
      if (slec.length != 1) {
        return this.$message.warning("请选择一条数据进行编辑");
      } else {
        this.saveForm_data = { ...slec[0] };
        this.$set(this.saveForm_data,"dataSourceNameLast",this.saveForm_data.dataSourceName.split('-')[1])
        this.isDataSrcMagAddOrEdit = true;
      }
    },
    saveFunc_data() {
      this.$refs["saveForm_data"].validate(valid => {
        if (valid) {
          
          let data = {
            ...this.saveForm_data
          };
          if(data.password != 'password' ){
            data.password = sm4.encryptWithECB(
                            this.key,
                            data.password
          )
          }
          data.dataSourceName = this.saveForm_data.moduleCode + '-'+this.saveForm_data.dataSourceNameLast
          systemManage.dataSrcSaveDs(data).then(res => {
            if (res.code == 200) {
              this.$message.success("保存成功");
              this.isDataSrcMagAddOrEdit = false;
              this.searchFunc_data();
            } else {
              this.$message.error(res.message || "保存失败");
            }
          });
        }
      });
    },
    delFunc_data() {
      let selection = this.$refs.dataSrcTable.selection;
      if (selection.length != 1) {
        return this.$message.warning("请选择一条数据进行删除");
      }
      this.$confirm("您确定要删除选中数据源吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let data = {
            dataSourceId: selection[0].dataSourceId,
            dataSourceName: selection[0].dataSourceName,
            moduleCode: selection[0].moduleCode
          };
          systemManage.dataSrcDelDs(data).then(res => {
            if (res.code == 200) {
              this.$message.success("删除成功");
              this.searchFunc_data();
            } else {
              this.$message.error(res.message || "删除失败");
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    dataSrcTableRowClick(row) {
      if (this.$refs.dataSrcTable) {
        this.$refs.dataSrcTable.clearSelection();
        this.$refs.dataSrcTable.toggleRowSelection(row, true);
      }
    },
    appModuleChange() {
      if (this.appMagForm.moduleCode) {
        let data = { moduleCode: this.appMagForm.moduleCode };
        systemManage.dataSrcQueryDsByModuleCode(data).then(res => {
          if (res.code == 200) {
            this.dataSrcList = res.datas;
            this.appMagForm.dsName = "";
          }
        });
      }
    },
    addAppFunc() {
      this.appMagForm.dsName = "";
      this.appMagForm.moduleCode = "";
      this.addAppDialog = true;
    },
    pushToAppList() {
      this.$refs["appMagForm"].validate(valid => {
        if (valid) {
          let data = {
            dsName: this.appMagForm.dsName,
            moduleCode: this.appMagForm.moduleCode
          };
          this.appList.push(data);
          this.addAppDialog = false;
        }
      });
    },
    saveAppList(){
      let objArr = this.appList
      for(let i = 0; i<this.appList.length-1;i++){
        for(let j = i+1;j<this.appList.length;j++){
          if(this.appList[i].moduleCode == this.appList[j].moduleCode){
            this.$message.warning('模块编码重复')
            return
          }
        }
      }
      let data = {datas:this.appList,projectId: this.appMagForm.projectId }
      systemManage.projectMgrModuleCodes(data).then(res=>{
        if(res.code==200){
          this.$message.success('授权应用成功')
          this.isAppMag = false;
          this.searchFunc()
        }else{
          this.$message.error(res.message)
        }
      })
    },
    handleSizeChange(val) {
      this.searchForm.size = val;
      this.searchFunc();
    },
    handleCurrentChange(val) {
      this.searchForm.page = val;
      this.searchFunc();
    },
    handleSizeChange_data(val) {
      this.searchFF.size = val;
      this.searchFunc_data();
    },
    handleCurrentChange_data(val) {
      this.searchFF.page = val;
      this.searchFunc_data();
    },
    saveFunc_test() {
      this.$refs["saveForm_data"].validate(valid => {
        if (valid) {
          let data = {
            ...this.saveForm_data
          };
          if(data.password != 'password'){
            data.password = sm4.encryptWithECB(
                            this.key,
                            data.password
                        )
          }
          data.dataSourceName = this.saveForm_data.moduleCode + '-'+this.saveForm_data.dataSourceNameLast
          systemManage.dataSrcTestDs(data).then(res => {
            if (res.code == 200) {
              this.$message.success("连接成功");
            } else {
              this.$message.error("连接失败,请检查输入信息");
            }
          });
        }
      });
    },
  }
};
</script>

<style lang="scss" scoped>
.dialogSearchBox {
  header {
    text-align: center;
    span {
      margin: 0 20px;
    }
  }
}
</style>